import Request from '@/js_sdk/luch-request/luch-request/index.js' // 下载的插件
import store from '@/store'
const http = new Request();

const codeVerificationArray = [200]
const handleCode = (code, msg) => {
	switch (code) {
		case 10001:
			uni.showModal({
				showCancel: false,
				title: `账号信息过期，请重新登录!`,
				success: function(res) {
					if (res.confirm) {
						store.commit('RESET_ALL')
						uni.reLaunch({
							url: "/pages/login"
						})
					}
				}
			})
			break;
		default:
			uni.showModal({
				showCancel: false,
				title: msg || `后端接口${code}异常，请联系开发人员!`
			})
			break;
	}
};

//加载
http.setConfig((config) => {
	// config.baseURL = `http://124.220.164.125:9000
	config.baseURL = `http://192.168.101.36:8080`;
	return config
})

http.interceptors.request.use((config) => {
	const token = store.state.user.token
	if (token) {
		config.header['Authorization'] = 'Bearer ' + token
	}
	return config
}, (error) => {
	return Promise.reject(error)
})


http.interceptors.response.use((response) => {
	const { data, config } = response;
	const { code, msg } = data;
	// 是否操作正常
	if (codeVerificationArray.includes(code)) {
		return response.data;
	} else {
		handleCode(code, msg);
		//可使promise状态进入catch   this.http.getList().catch(err=>{})
		return Promise.reject(
			"自用请求异常拦截:" +
			JSON.stringify({ url: config.url, code, msg }) || "自用Error"
		);
	}
}, (error) => {
	// 报错后代码不会继续往后执行
	/*
	 只有以下情况才会进入这里：
		1.请求没发出去errMsg: "request:fail"
		2.HTTP的statuCode不是200 譬如token过期
		[注]有rawData说明是后端代码主动设置的statuCode不是200,另外还给了msg
	 */
	console.log(`error`, error);
	if (error.rawData) { // 
		const { code, msg } = error.rawData;
		handleCode(code, msg);
		return Promise.reject(error);
	} else {
		let { errMsg } = error;
		if (errMsg.includes("Network") || errMsg.includes("timeout") || errMsg.includes(
				"request")) {
			errMsg = '网络开小差了'
		}
		uni.showModal({
			showCancel: false,
			title: errMsg
		})
		return Promise.reject(error);
	}
})

export default http;